package com.lagou.core.web;

import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

import java.util.Collections;

public class TomcatWebServerFactory implements MyWebServerFactory {

    @Override
    public void createWebServer(MyServletContextInitializer... initializer) throws Exception {
        Tomcat tomcat = new Tomcat();
        String baseDir = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        tomcat.setBaseDir(baseDir);
        tomcat.setPort(8080);
        //tomcat.setConnector(new Connector());
        tomcat.addWebapp("/", baseDir);
        tomcat.enableNaming();

        StandardContext context = new StandardContext();
        context.setName("my-context");
        context.setPath("/");
        context.addLifecycleListener(new Tomcat.FixContextListener());
        // 编程式添加ServletContainerInitializer
        context.addServletContainerInitializer(new TomcatStarter(initializer), Collections.emptySet());
        tomcat.getHost().addChild(context);
        tomcat.getHost().setAutoDeploy(false);

        tomcat.start();
        tomcat.getServer().await();
    }

}
